<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\common\model;

use app\common\controller\Backend;
use app\common\model\User;
use fast\Random;
use GuzzleHttp\Client;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 教师
 *
 * Class Teacher
 * @package app\admin\controller
 */
class Teacher extends Backend
{
    /**
     * @var \app\common\model\Teacher
     */
    protected $model = null;
    protected $searchFields = 'name';
    protected $noNeedRight = ['searchList', 'cxSelect', 'formSelects'];
    protected $schoolLimit = true;
    protected $relationSearch = true;
    protected $modelValidate = true;
    protected $modelSceneValidate = true;
    protected $genderData = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Teacher');

        $this->genderData = model\User::getGenderList();
        $this->view->assign('genderData', $this->genderData);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model->alias('teacher')
                ->join("__USER__ user", 'teacher.user_id = user.id')
                ->join("__SCHOOL__ school", 'school.id = teacher.school_id')
                ->where($where)
                ->count();

            $list = $this->model->alias('teacher')
                ->join("__USER__ user", 'teacher.user_id = user.id')
                ->join("__SCHOOL__ school", 'school.id = teacher.school_id')
                ->where($where)
                ->field('teacher.*,user.username,user.nickname,user.gender,user.mobile,school.name school_name')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                $list = collection($list)->append(['gender_text'])->toArray();
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $user_params = $this->request->post("user/a");

            if ($params && $user_params) {

                if (!$params['school_id']) {
                    $this->error('请选择学校');
                }

                if (!$params['avatar']) {
                    $this->error('请上传头像');
                }

                $user_params['nickname'] = $params['name'];
                $user_params['avatar'] = $params['avatar'];
                $user_params['gender'] = $params['gender'];

                $result = false;
                Db::startTrans();
                try {

                    $user = model\User::getUser($user_params['mobile'], $user_params['nickname'], ['avatar' => $user_params['avatar'], 'gender'=> $user_params['gender'], 'school_id' => $this->auth->school_id]);
                    if (isset($user['error'])) {
                        $this->error($user['error']);
                    }

                    $count = model\Teacher::where('user_id', $user->id)->count();
                    if ($count) {
                        $this->error('教师已存在');
                    }

                    $params['user_id'] = $user->id;
                    $result = $this->model->allowField(true)->save($params);

                    $client = new Client([
                        'base_uri' => config('suzhi.url'),
                        'timeout' => 30,
                        'allow_redirects' => true
                    ]);
                    $response = $client->request('POST', '/platform/user/add', [
                        'form_params' => [
                            'id' => $user->id,
                            'school_id' => $params['school_id'],
                            'name' => $user_params['nickname'],
                            'gender' => $user_params['gender'],
                            'mobile' => $user_params['mobile'],
                            'avatar' => config('app_url') . $user_params['avatar'],
                        ]
                    ]);
                    $content = $response->getBody();
                    $content = json_decode($content, true);
                    $result2 = false;
                    if (isset($content['error_code']) && $content['error_code'] == 0) {
                        $result2 = true;
                    }

                    if ($result && $result2) {
                        Db::commit();
                    } else {
                        Db::rollback();
                        $this->error(isset($content['msg']) ? $content['msg'] : '添加失败');
                    }

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->with('user')->where('id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            $user_params = $this->request->post("user/a");

            if ($params) {

                if ($user_params) {
                    $validate = Validate('User');
                    $res = $validate->scene('edit')->check($user_params);
                    if (!$res) {
                        $this->error($validate->getError());
                    }
                }

                $result = false;
                Db::startTrans();
                try {

                    $result = $row->allowField(true)->save($params);

                    $user_params['username'] = $user_params['mobile'];
                    $user_params['nickname'] = $params['name'];
                    $user_params['avatar'] = $params['avatar'];
                    $user_params['gender'] = $params['gender'];
                    model\User::where('id', $row->user_id)->update($user_params);

                    $client = new Client([
                        'base_uri' => config('suzhi.url'),
                        'timeout' => 30,
                        'allow_redirects' => true
                    ]);
                    $response = $client->request('POST', '/platform/user/edit', [
                        'form_params' => [
                            'id' => $row->user_id,
                            'school_id' => $params['school_id'],
                            'name' => $user_params['nickname'],
                            'gender' => $user_params['gender'],
                            'mobile' => $user_params['mobile'],
                            'avatar' => config('app_url') . $user_params['avatar'],
                            'role' => 1,
                        ]
                    ]);
                    $status = $response->getStatusCode();

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $schoolIds = $this->getDataLimitSchoolIds();
            if (is_array($schoolIds)) {
                $this->model->where($this->schoolLimitField, 'in', $schoolIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            Db::startTrans();
            try {
                $delete_ids = array_column($list, $pk);
                $delete_user_ids = array_column($list, 'user_id');

//                $this->model->whereIn('id', $delete_ids)->delete();
//                User::whereIn('id', $delete_user_ids)->delete();

                $this->model->destroy($delete_ids);
                User::destroy($delete_user_ids);

                $client = new Client([
                    'base_uri' => config('suzhi.url'),
                    'timeout' => 30,
                    'allow_redirects' => true
                ]);
                $response = $client->request('POST', '/platform/user/del', [
                    'form_params' => [
                        'ids' => $delete_user_ids,
                    ]
                ]);
                $status = $response->getStatusCode();

                Db::commit();

                $this->success();

            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 搜索下拉列表
     */
    public function searchList()
    {
        $school_id = $this->request->request('school_id');
        $result = $this->model->with('user')->where('school_id', $school_id)->select();

        $searchlist = [];
        foreach ($result as $key => $value) {
            $searchlist[] = ['id' => $value['id'], 'name' => $value['user']['nickname']];
        }
        $data = ['searchlist' => $searchlist];
        $this->success('', null, $data);
    }

    /**
     * 联动搜索
     * 根据楼栋号获取寝室列表
     */
    public function cxSelect()
    {
        $school_id = $this->request->request('school_id');
        $result = $this->model->alias('teacher')->with('user')->where('teacher.school_id', $school_id)->select();

        $searchList = [];
        foreach ($result as $key => $value) {
            $searchList[] = ['value' => $value['id'], 'name' => $value['user']['nickname']];
        }

        $this->success('', null, $searchList);
    }

    public function formSelects()
    {
        $school_id = $this->request->request('school_id');
        $result = $this->model->with('user')->where('school_id', $school_id)->select();

        $data = [];
        foreach ($result as $key => $value) {
            $data[] = ['value' => $value['id'], 'name' => $value['user']['nickname']];
        }

        return json_encode($data);
    }




}
